<?php

use Freyo\Flysystem\QcloudCOSv5\Adapter;
use League\Flysystem\Filesystem;
use Qcloud\Cos\Client;

include __DIR__ . '/vendor/autoload.php';

$config = [
    'region'          => 'ap-guangzhou',
    'credentials'     => [
        # codepku scratch works
        # 'appId'     => '1253386414',
        # 'secretId'  => 'AKIDYw63nIGcR2PYTAosseCWcU9ZljTyJH5k',
        # 'secretKey' => 'Zu0tXx97rNfjZBZjeLo22oMgmfLn10lI',
        # wanxue game
        'appId'     => '1305728470',
        'secretId'  => 'AKIDtfEbkeJjtoUw97sNcbLq8B0aw3uWt1uX',
        'secretKey' => 'UigOq3zjiTQ7aomWnrgFYdU5QWMxINDp',

        'token'     => null,
    ],

    # 'bucket'    => 'scratch-works-1253386414',
    'bucket'    => 'wxsj-worlds-1305728470',
    'timeout'         => 60,
    'connect_timeout' => 60,
    'cdn'             => '',
    'scheme'          => 'https',
    'read_from_cdn'   => false,
    'cdn_key'         => '',
    'encrypt'         => false,
];
$client     = new Client($config);
$adapter    = new Adapter($client, $config);
$filesystem = new Filesystem($adapter);

function deleteFromCos($paths){
    global $client, $adapter;
     $keys = array_map(function($p){
         $p = ltrim($p, '/');
         $p = rtrim($p);
         if(strlen($p) > 0){
             return ['Key' => $p];
         }
     }, $paths);
     $keys = array_filter($keys); // remove null values ( last line etc.)
     if(count($keys) == 0) return 0;

     $ret = $client->deleteObjects([
             'Bucket' => $adapter->getBucketWithAppId(),
             'Objects' => $keys
     ]);
     if(count($ret['Deleted']) == count($keys)){
             echo "Deleted " . count($keys) . " files successfully " . $paths[count($paths) - 1] . "\n";
             return true;
     }else{
             echo "Some files failed\n";
             return false;
     }
}

function deleteFromFile(){
    $filename = "todelete.log";
    echo "start to process files from cos\n";
    echo "open file for reading\n";
    $readFile = new \SplFileObject($filename, "r");
    $batchPaths = [];
    while(! $readFile->eof()){
        $batchPaths[] = $readFile->fgets();
        if(count($batchPaths) >= 1000){
            deleteFromCos($batchPaths);
            $batchPaths = [];
        }
    }
    // 最后一批不足999个
    if(count($batchPaths) > 0){
        deleteFromCos($batchPaths);
    }
    echo "Totally deleted " . $readFile->key() . " files \n";

    return 0;
}

deleteFromFile();

